package com.jf.blog.util;

import com.jf.blog.bean.Userinfo;
import com.jf.blog.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginUtil {
    private static StringRedisTemplate redisTemplate;
    private static UserinfoService userinfoService;
    private static HttpServletRequest request;

    @Autowired
    private LoginUtil(StringRedisTemplate redisTemplate, UserinfoService userinfoService, HttpServletRequest request) {
        LoginUtil.redisTemplate = redisTemplate;
        LoginUtil.userinfoService = userinfoService;
        LoginUtil.request = request;
    }

    public static Userinfo getLoginUser() {
        String token = request.getHeader(MyConstants.TOKEN);
        String value = redisTemplate.opsForValue().get(MyConstants.TOKEN_KEY + token);
        assert value != null;
        int userinfoId = Integer.parseInt(value);
        return userinfoService.getById(userinfoId);
    }
}
